package com.elong.android.specialhouse.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.elong.android.specialhouse.ApartmentAPI;
import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.account.Account;
import com.elong.android.specialhouse.base.DialogUtils;
import com.elong.android.specialhouse.entity.response.OrderDetail;
import com.elong.android.specialhouse.request.GetOrderDetailRequst;
import com.elong.android.specialhouse.request.modifyOrderReq;
import com.elong.android.specialhouse.ui.CircleImageView;
import com.elong.android.specialhouse.utils.DateTimeUtils;
import com.elong.android.specialhouse.utils.StringUtils;
import com.elong.android.specialhouse.utils.ToastUtils;
import com.elong.framework.netmid.ElongRequest;
import com.elong.framework.netmid.response.IResponse;
import com.elong.framework.netmid.response.StringResponse;
import com.elong.payment.base.PaymentConstants;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 房客模式下的订单详情
 *
 * @author boyan
 */
public class MyOrderDetailActivity extends OrderDetailActivity {
    public static final String SELF = "com.elong.android.youfang.activity.MyOrderDetailActivity";
    private static final int REQUEST_ACTIVITY_PAYMENT = 0;
    /*催单*/
    public static final int TYPE_REMIND = 1;
    /*我已入住*/
    public static final int TYPE_HAD_CHECKED_IN = 2;
    /*点评*/
    public static final int TYPE_GO_TO_EVALUATION = 3;

    /*酒店地址*/
    private TextView mHouseAddresstv;
    /*酒店名称*/
    private TextView mHouseNametv;
    /*房东名称*/
    private TextView mLandlordNametv;
    /*展示“房东”的位置*/
    private TextView mLandlordTiptv;
    /*房东电话*/
    private TextView mLandlordNumbertv;
    /*联系ta*/
    private TextView mConnectLandlordtv;
    /*房东页面中房客留言的信息*/
    private LinearLayout mMessageLayout;
    private CircleImageView mLandlordImg;
    private int mOtherBtnType = -1;//1：催单 2：我已入住 3：点评
    private String mCancelHint;

    @Override
    protected void initview() {
        setHeader(R.string.order_detail);
        mGorderId = getIntent().getStringExtra("mGorderId");
        View v = View.inflate(this, R.layout.layout_client_order_other_message, mDifferentLayout);
        mHouseAddresstv = (TextView) v.findViewById(R.id.tv_hotel_adress);
        mHouseAddresstv.setOnClickListener(this);
        mHouseNametv = (TextView) v.findViewById(R.id.tv_hotel_name);
        mLandlordTiptv = (TextView) v.findViewById(R.id.tv_client_tip);
        mLandlordTiptv.setText(R.string.landlord);
        mLandlordNametv = (TextView) v.findViewById(R.id.tv_client_name);
        mLandlordNumbertv = (TextView) v.findViewById(R.id.tv_client_phone);
        mLandlordNumbertv.setOnClickListener(this);
        mConnectLandlordtv = (TextView) v.findViewById(R.id.tv_connect_client);
        mConnectLandlordtv.setOnClickListener(this);
        mLandlordImg = (CircleImageView) v.findViewById(R.id.img_client_photo);
        mLandlordImg.setOnClickListener(this);
        mMessageLayout = (LinearLayout) v.findViewById(R.id.ly_message);
        mMessageLayout.setVisibility(View.GONE);
        mOrderLogTv.setOnClickListener(this);
        mBtnOther.setOnClickListener(this);
        mBtnNegative.setOnClickListener(this);
        mBtnGoToPay.setOnClickListener(this);
        mHouseNametv.setOnClickListener(this);
        setData();
    }

    private void setData() {
        GetOrderDetailRequst param = new GetOrderDetailRequst();
        param.GorderId = mGorderId;
        if (Account.getInstance().currentIsCustomer()) {
            param.UserType = 0;
        } else {
            param.UserType = 1;
        }
        param.TagType = 1;
        requestHttp(param, ApartmentAPI.orderDetail, StringResponse.class, true);

    }

    @Override
    public void onTaskPost(ElongRequest request, IResponse<?> t) {
        super.onTaskPost(request, t);
        JSONObject result = (JSONObject) JSONObject.parse(((StringResponse) t).getContent());
        switch (((ApartmentAPI) request.getRequestOption().getHusky())) {
            case orderDetail:
                if (result.getBoolean("IsError")) {
                    String message = result.getString("ErrorMessage");
                    ToastUtils.show(this, message);
                } else {
                    mOrderDetail = JSON.parseObject(result.toJSONString(), OrderDetail.class);
                    mOrderNumTv.setText(mOrderDetail.OrderId);
                    mOrderStatusTv.setText(mOrderDetail.OrderStatusDesc);
                    String checkintime = DateTimeUtils.changeDateFormat(mOrderDetail.ArriveDate);
                    String leavetime = DateTimeUtils.changeDateFormat(mOrderDetail.LeaveDate);
                    mCheckinTimeTv.setText(checkintime + "-" + leavetime);
                    mHousePriceTv.setText("￥" + mOrderDetail.GorderAmount);
                    mClientCountTv.setText(Integer.valueOf(mOrderDetail.CustomCount).toString() + "人");
                    mClientNameTv.setText(mOrderDetail.CustomName);
                    //设置位置信息
                    String address = TextUtils.isEmpty(mOrderDetail.ApartmentAddress) ? "" : mOrderDetail.ApartmentAddress;
                    //去除分隔符
                    address = address.replace(AppConstants.HOUSE_LOCATION_SPLIT, "");
                    mHouseAddresstv.setText("地址：" + address);
                    mHouseNametv.setText(mOrderDetail.ApartmentName);
                    mLandlordNametv.setText(mOrderDetail.LandlordName);
                    if (mOrderDetail.OrderStatus >= 2 && mOrderDetail.OrderStatus != 5) {
                        mLandlordNumbertv.setText(mOrderDetail.LandlordMobile);
                        mLandlordNumbertv.setVisibility(View.VISIBLE);
                    } else {
                        mLandlordNumbertv.setVisibility(View.GONE);
                    }

                    mConnectLandlordtv.setText(R.string.contact_with_landlord);
                    mCancelRuleTv.setText(mOrderDetail.Rule);
                    setButtonStatus(mOrderDetail.IsCanCancel, mOrderDetail, mOrderDetail.PayStatus);
                    if (mOrderDetail.ImageUrl != null && !TextUtils.isEmpty(mOrderDetail.ImageUrl)) {
                        ImageLoader.getInstance().displayImage(mOrderDetail.ImageUrl, mLandlordImg);
                    }
                    showDetail();
                }
                break;
            case orderCancel:
                if (result.getBoolean("IsError")) {
                    ToastUtils.show(this, result.getString("ErrorMessage"));
                } else {
                    setData();
                }
                break;
            case orderUrge:
                if (result.getBoolean("IsError")) {
                    ToastUtils.show(this, result.getString("ErrorMessage"));
                } else {
                    ToastUtils.show(this, R.string.reminder_order);
                }
                break;
            case userConfirmCheckIn:
                if (result.getBoolean("IsError")) {
                    ToastUtils.show(this, result.getString("ErrorMessage"));
                } else {
                    setData();
                }
                break;
        }
    }

    /**
     * 设置按钮状态
     *
     * @param isCanCancel
     * @param mOrderDetail
     * @param payStatus   MY_ORDER_STATUS_NEW_ORDER=0;
     *                    public final static int MY_ORDER_STATUS_CONNECT_ORDER=1;
     *                    public final static int MY_ORDER_STATUS_RESERVE_SUCCEED=2;
     *                    public final static int MY_ORDER_STATUS_CANCEL_ORDER=5;
     *                    public final static int MY_ORDER_STATUS_ALREADY_CHECKIN=6;
     *                    public final static int MY_ORDER_STATUS_ORDER_FINISH=10;
     */
    private void setButtonStatus(Boolean isCanCancel, OrderDetail mOrderDetail, Integer payStatus) {
        if (mOrderDetail.UrgeBttn) {
            mBtnOther.setText(R.string.remind_landlord);
            mOtherBtnType = TYPE_REMIND;
            mBtnOther.setVisibility(View.VISIBLE);
            mBottomButtonLayout.setVisibility(View.VISIBLE);
        }
        if (mOrderDetail.ConfirmCheckInBttn) {
            mBtnOther.setText(R.string.had_checked_in);
            mOtherBtnType = TYPE_HAD_CHECKED_IN;
            mBtnOther.setVisibility(View.VISIBLE);
            mBottomButtonLayout.setVisibility(View.VISIBLE);
        }
        if (mOrderDetail.CommentBttn) {
            mBtnOther.setText(R.string.go_to_evaluation);
            mOtherBtnType = TYPE_GO_TO_EVALUATION;
            mBtnOther.setVisibility(View.VISIBLE);
            mBottomButtonLayout.setVisibility(View.VISIBLE);
        }
        if (isCanCancel) {
            mBtnNegative.setVisibility(View.VISIBLE);
            mBottomButtonLayout.setVisibility(View.VISIBLE);
        } else {
            mBottomButtonLayout.setVisibility(View.GONE);
        }
        if (mOrderDetail.PayBttn) {
            mBtnGoToPay.setVisibility(View.VISIBLE);
            mBottomButtonLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_go_to_order_detail:
                Intent in = new Intent(this, OrderLogActivity.class);
                in.putExtra(AppConstants.ORDER_ID, mOrderDetail.OrderId);
                startActivity(in);
                break;
            case R.id.tv_client_phone:
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mLandlordNumbertv.getText().toString()));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
            case R.id.tv_connect_client:
                //启动即时通讯工具
//			goToEvaluationActivity();
                gotoChatActivity();
                break;
            case R.id.tv_hotel_name:
                gotoApartmentDetailActivity();
                break;
            case R.id.tv_hotel_adress:
                gotoMapActivity();
                break;
            case R.id.btn_order_detail_btn1:
//			statusHasChanged = true;
                switch (mOtherBtnType) {
                    case TYPE_REMIND:
                        urgeOrder();
                        break;
                    case TYPE_HAD_CHECKED_IN:
                        userConfirmCheckIn();
                        break;
                    case TYPE_GO_TO_EVALUATION:
                        goToEvaluationActivity();
                        break;
                    default:
                        break;
                }
                break;
            case R.id.btn_order_detail_negative:
                cancelOrder();
                break;
            case R.id.btn_go_to_pay:
                goToPay();
                break;
            case R.id.common_head_back:
                onBackClicked();
                break;
            case R.id.img_client_photo:
                goToHomePageOthers(mOrderDetail.LandloardId + "", mOrderDetail.LandlordName);
                break;
        }
        super.onClick(v);
    }

    /**
     * 查看他人的个人主页
     */
    private void goToHomePageOthers(String uid,String name) {
        Intent intent = new Intent(this,HomePageOthersActivity.class);
        intent.putExtra(AppConstants.LANDLORD_ID,uid);
        intent.putExtra(AppConstants.LANDLORD_NAME,name);
        startActivity(intent);
    }
    /**
     * 启动公寓详情页
     */
    private void gotoApartmentDetailActivity() {
        Intent intent = new Intent(MyOrderDetailActivity.this, ApartmentDetailsActivity.class);
        intent.putExtra(AppConstants.APARTMENT_ID, mOrderDetail.ApartmentId);
        startActivity(intent);
    }

    /**
     * 启动评价页面
     */
    private void goToEvaluationActivity() {
        Intent intent = new Intent(MyOrderDetailActivity.this, PublishEvaluationActivity.class);
        intent.putExtra(AppConstants.CHECKIN_DATE_TIME, mOrderDetail.ArriveDate);
        intent.putExtra(AppConstants.CHECKOUT_DATE_TIME, mOrderDetail.LeaveDate);
//		intent.putExtra(PublishEvaluationActivity.ORDERDETAIL, mOrderDetail);
        intent.putExtra(AppConstants.APARTMENT_NAME, mOrderDetail.ApartmentName);
        intent.putExtra(AppConstants.ORDER_ID, mOrderDetail.OrderId);
        intent.putExtra(AppConstants.GORDER_ID, mOrderDetail.GorderId);
        intent.putExtra(AppConstants.HOUSE_ID, mOrderDetail.ApartmentId);
        intent.putExtra(AppConstants.HOUSE_IAMGE_URL, mOrderDetail.HouseImageUrl);
        startActivity(intent);

    }

    /**
     * 启动公寓地图页面
     */
    private void gotoMapActivity() {
        Intent intent = new Intent(MyOrderDetailActivity.this, ApartmentMapActivity.class);
        intent.putExtra(AppConstants.ACTIVITY_KEY_HOUSE_BAIDU_LATITUDE, mOrderDetail.BaiduLat == null ? null : mOrderDetail.BaiduLat + "");
        intent.putExtra(AppConstants.ACTIVITY_KEY_HOUSE_BAIDU_LONGITUDE, mOrderDetail.BaiduLon == null ? null : mOrderDetail.BaiduLon + "");
        intent.putExtra(AppConstants.ACTIVITY_KEY_HOUSE_ADDRESS, mOrderDetail.ApartmentAddress);
        startActivity(intent);
    }

    /**
     * 取消订单
     */
    private void cancelOrder() {
        if (StringUtils.isNotEmpty(mOrderDetail.CancelPromptNote)) {
            mCancelHint = getResources().getString(R.string.cancel_rules);
        } else {
            mCancelHint = getResources().getString(R.string.order_cancel_hint);
        }
        DialogUtils.showConfirmDialog(this, mCancelHint, mOrderDetail.CancelPromptNote,
                new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        if (isWindowLocked()) {
                            return;
                        }
                        if (which == DialogInterface.BUTTON_POSITIVE) {
                            doCancelOrder();
                        }
                    }
                });
    }

    /**
     * 取消订单操作
     */
    private void doCancelOrder() {
        modifyOrderReq mparam = new modifyOrderReq();
        mparam.OrderId = mOrderDetail.OrderId;
        mparam.UserId = Account.getInstance().getUserId();
        requestHttp(mparam, ApartmentAPI.orderCancel, StringResponse.class, true);
    }

    /**
     * 催单按钮
     */
    private void urgeOrder() {
        modifyOrderReq mparam = new modifyOrderReq();
        mparam.GorderId = mGorderId;
        requestHttp(mparam, ApartmentAPI.orderUrge, StringResponse.class, true);
    }

    /**
     * 确认入住
     */
    private void userConfirmCheckIn() {
        modifyOrderReq mparam = new modifyOrderReq();
        mparam.OrderId = mOrderDetail.OrderId;
        requestHttp(mparam, ApartmentAPI.userConfirmCheckIn, StringResponse.class, true);
    }

    /**
     * 联系他
     */
    private void gotoChatActivity() {
        Intent intent = new Intent(MyOrderDetailActivity.this, ChatActivity.class);
        intent.putExtra(AppConstants.ACTIVITY_KEY_FRIEND_ID, mOrderDetail.LandloardId);
        intent.putExtra(AppConstants.ACTIVITY_KEY_FRIEND_NAME, mOrderDetail.LandlordName);
        startActivity(intent);
    }

    /**
     * 只支付页面
     */
    private void goToPay() {
//    	TODO 去支付的跳转
        Intent intent = new Intent(this, BookingSubmitedActivity.class);
        intent.putExtra(PaymentConstants.orderId, mOrderDetail.OrderId);
        intent.putExtra(PaymentConstants.gorderId, mGorderId);
        intent.putExtra(PaymentConstants.totalPrice, Double.valueOf(mOrderDetail.GorderAmount));
//        intent.putExtra(PaymentConstants.hotelName, mOrderDetail.ApartmentName);
        intent.putExtra(PaymentConstants.hotelName, mOrderDetail.ApartmentName);
        intent.putExtra(PaymentConstants.isCanback, false);

//        String checkinDate = DateTimeUtils.parseStringDate(mOrderDetail.ArriveDate);
//        String checkoutDate = DateTimeUtils.parseStringDate(mOrderDetail.LeaveDate);
//        if (!TextUtils.isEmpty(checkinDate)) {
//            intent.putExtra(PaymentConstants.checkinDate, mOrderDetail.ArriveDate);
//        }
//        if (!TextUtils.isEmpty(checkoutDate)) {
//            intent.putExtra(PaymentConstants.checkoutDate, mOrderDetail.LeaveDate);
//        }
//        int totaldays = DateTimeUtils.getIntervalDays(mOrderDetail.ArriveDate,
//                mOrderDetail.LeaveDate, "yyyy-MM-dd");
//        intent.putExtra(PaymentConstants.totalsDays, Integer.valueOf(totaldays).toString());

        //标识是继续支付，即不是从预定完成后直接去支付，而是从订单列表或者详情页中去支付的
        intent.putExtra(AppConstants.KEY_IS_CONTINUE_PAY, true);
        intent.putExtra(AppConstants.BUNDLE_KEY_COME_FROM, SELF);
        startActivity(intent);
        startActivityForResult(intent, REQUEST_ACTIVITY_PAYMENT);
    }

    private void onBackClicked() {
        back();
//		if (getIntent().getBooleanExtra(AppConstants.KEY_IS_FROM_ORDER_LIST_PAGE,true)){
//			//来自列表页
//			back();
//		}else {
//			//不是来自列表页
//			Utils.clearActivityStack();
//			startActivity(TabHomeActivity.class,null);
//		}
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackClicked();
        }
        return super.onKeyDown(keyCode, event);
    }
}
